package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录检查
 * 需默认实现
 */
public class CheckLoginInterceptor implements HandlerInterceptor{

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    //登录检查
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        /*//1. 获取token
        String token = CookieUtil.getToken(request, response);

        //2. 通过token作为key值查询当前用户对象
        UserInfo user = userInfoRedisService.getUserByToken(token);
        if (user == null){
            response.sendRedirect("/login.html");
            return false;
        }*/

        String token = CookieUtil.getToken(request, response);
        //1. 获取当前请求方法的对象
        UserInfo user = userInfoRedisService.getUserByToken(token);
        //拦截器可以拦截所有请求包括动态, 静态, 动态请求方法对象(handlermethod)
        //静态请求对象不是handlermethod对象处理
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            //2. 判断该请求方法是否贴了@RequireLogin注解
            if (handlerMethod.hasMethodAnnotation(RequireLogin.class)) {
                //3. 如果贴了, 需要判断该用户是否登录
                if (user == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        //如果没贴, 放行
        //让所有请求都可以共享用户对象信息
        request.getSession().setAttribute("userInfo", user);
        return true;
    }
}
